package com.daily.pump.http;


import android.text.TextUtils;

import com.daily.pump.app.App;
import com.daily.pump.http.api.ApiService;
import com.daily.pump.utils.MD5;
import com.daily.pump.utils.NetworkUtil;
import com.xunxi.mimi.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者: liyu on  2017/9/26 16:58
 * 邮箱：liyu@szy.cn
 * 功能描述:
 * 备注:
 */
public class HttpManager {

    public static final String PATH_DATA = App.getInstance().getCacheDir().getAbsolutePath() + File.separator + "data";
    public static final String PATH_CACHE = PATH_DATA + "/NetCache";
    private static HttpManager mInstance;

    private OkHttpClient mOkHttpClient;
    private Retrofit mRetrofit;

    public static HttpManager getInstance() {
        synchronized (HttpManager.class) {
            if (mInstance == null) {
                mInstance = new HttpManager();
            }
        }
        return mInstance;
    }

    public HttpManager() {
        initClient();
        initRetrofit();
    }

    private void initClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        File cacheFile = new File(PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        //设置缓存
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
//        builder.addInterceptor(signInterceptor);
        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        mOkHttpClient = builder.build();
    }

    private void initRetrofit() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiService.BASE_URL)
                .client(mOkHttpClient)
                .addConverterFactory(WrapperConverterFactory.create())//加入json解析
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 使用RxJava作为回调适配器
                .build();
    }

    private Interceptor cacheInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            LogUtil.error(HttpManager.class, "RequestUrl: " + request.url().toString());
            if (!NetworkUtil.isNetAvailable()) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Headers.Builder headerBuilder = request.headers().newBuilder()
                    .add("deviceType", "1");//1安卓  2ios

            Headers headers = headerBuilder.build();
            request = request.newBuilder().headers(headers).build();

            Response response = chain.proceed(request);
            if (NetworkUtil.isNetAvailable()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")
                        .build();
            } else {
                // 无网络时，设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }
            return response;
        }
    };

    private Interceptor signInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (TextUtils.isEmpty(request.header("timestamp"))) {
                String key = "YqH3DGpu";
                String timestamp = String.valueOf(System.currentTimeMillis());
                String sign = MD5.hexdigest(key + timestamp).toUpperCase();
                request.newBuilder()
                        .addHeader("timestamp", timestamp)
                        .addHeader("sign", sign)
                        .build();
            }
            return chain.proceed(request);
        }
    };

    public ApiService provideApiService() {
        return mRetrofit.create(ApiService.class);
    }

    public void clearRetrofit() {
        mInstance = null;
    }
}
